package com.itheima.sfbx.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {

    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE, key = "#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, Integer pageNum, Integer pageSize) {

        try {
            LambdaQueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            //执行分页查询
            Page<Safeguard> page = new Page<>(pageNum, pageSize);
            Page<Safeguard> safeguardPage = page(page, queryWrapper);
            //返回结果
            return BeanConv.toPage(safeguardPage, SafeguardVO.class);
        } catch (Exception e) {
            log.error("查询保障项列表失败：{}", e);
            throw new ProjectException(SafeguardEnum.PAGE_FAIL);
        }
    }

    @NotNull
    private static LambdaQueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO) {
        //构建分页查询对象
        LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
        //规则键查询
        queryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKey()),
                Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey());
        //条例键名称模糊查询
        queryWrapper.like(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKeyName()),
                Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName());
        //状态查询
        queryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getDataState()),
                Safeguard::getDataState, safeguardVO.getDataState());
        //根据创建时间降序排序
        queryWrapper.orderByDesc(Safeguard::getCreateTime);
        //上述查询条件对象中对应的sql where order子句是什么：
        //where safeguard_key=?and safeguard_key_name like ? and data_state=?order by create_time desc
        return queryWrapper;
    }

    @Override
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)},
            put = {@CachePut(value = SafeguardCacheConstant.BASIC, key = "#result.id")})
    public SafeguardVO save(SafeguardVO safeguardVO) {

        try {
            //封装成实体对象
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            //保存
            boolean flag = save(safeguard);
            //判断保存结果
            if (!flag) {
                throw new RuntimeException("保存保障项失败");
            }
            return BeanConv.toBean(safeguard, SafeguardVO.class);
        } catch (Exception e) {
            log.error("保存保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));//获取异常栈信息
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC, key = "#safeguardId")
    public SafeguardVO findById(String safeguardId) {
        try {
            //执行查询
            return BeanConv.toBean(getById(safeguardId), SafeguardVO.class);
        } catch (Exception e) {
            log.error("保障项单条查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
    }

    @Override
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)},
            put = {@CachePut(value = SafeguardCacheConstant.BASIC, key = "#safeguardVO.id")}
    )
    public Boolean update(SafeguardVO safeguardVO) {

        try {
            //封装成实体对象
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            boolean flag = updateById(safeguard);
            if (!flag) {
                throw new RuntimeException("修改保障项失败");
            }
            return flag;
        } catch (Exception e) {
            log.error("修改保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
    }

    @Override
    @Caching(
            evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.BASIC, allEntries = true)
            }
    )
    public Boolean delete(String[] checkedIds) {
        try {
            //将字符串数组转换为Long数组
            List<Long> idsList = Arrays.asList(checkedIds).stream().map(Long::valueOf).collect(Collectors.toList());
            boolean flag = removeByIds(idsList);
            if (!flag) {
                throw new RuntimeException("删除保障项失败");
            }
            return flag;
        } catch (Exception e) {
            log.error("删除保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST, key ="#safeguardVO.hashCode()")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        try {
            LambdaQueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            List<Safeguard> list = list(queryWrapper);
            if (!EmptyUtil.isNullOrEmpty(list)) {
                return BeanConv.toBeanList(list, SafeguardVO.class);
            }
        } catch (Exception e) {
            log.error("查询保障项列表失败；{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.LIST_FAIL);
        }
        return List.of();
    }

    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        return null;
    }
}
